import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_category_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_one_details_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_set_backup_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_set_image_category_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_set_image_style_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_style_type_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_upload_service.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../app_main.dart';

///智能家居上传确认页面
class SmartHomeUploadConfirmPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "SmartHomeUploadConfirmPage";

  final List<SmartHomeUploadItemBean> itemList;
  final String shid;
  //上传完成后回到的页面
  final String router;
  final List<SpatialTypeListBean> categoryList;

  const SmartHomeUploadConfirmPage({Key key, this.itemList, this.shid, this.router, this.categoryList}):super(key:key);
  ///跳转方法
  static Future<bool> navigatorPush(BuildContext context,
      List<SmartHomeUploadItemBean> itemList, String shid, List<SpatialTypeListBean> categoryList, {String router}){
    return RouterUtils.routeForFutureResult(
      context,
      SmartHomeUploadConfirmPage(
        itemList: itemList,
        shid: shid,
        router: router,
        categoryList: categoryList,
      ),
    );
  }

  @override
  _SmartHomeUploadConfirmPageState createState() => _SmartHomeUploadConfirmPageState();

}

class _SmartHomeUploadConfirmPageState extends BaseState<SmartHomeUploadConfirmPage>{
  ScrollController _scrollController;
  double _imgContainerWidth = 0;
  double _imgContainerHeight = 0;
  SmartHomeStoreDetailViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = new SmartHomeStoreDetailViewModel(this);
    _scrollController = ScrollController();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: true,
          resizeToAvoidBottomPadding: true,
          backgroundColor: Color(0xFFF6F7F9),
          body: _toMainColumnWidget(),
        )
    );
  }


  @override
  void dispose() {
    super.dispose();
  }


  Widget _toMainColumnWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        SizedBox(height: 10,),
        _toGridPage(),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "上传文件",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toSaveButtonWidget(),
    );
  }

  Widget _toSaveButtonWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        _upload();
      },
      child: Container(
        width: 48,
        height: 24,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Text(
            "上传",
          style: TextStyle(
            color: Colors.white,
            fontSize: 12,
            height: 1.2,
          ),
        ),
      ),
    );
  }

  String getDefaultStid(){
    String stid = "";
    widget?.categoryList?.forEach((element) {
      if("其他" == element?.name){
        stid = element?.stid;
      }
      print("getDefaultStid:" + element?.name + ", stid:" + element?.stid);
    });
    print("getDefaultStid:" +stid);
    return stid;
  }

  void _upload(){
    if(widget?.itemList?.length == 1 && StringUtils.isNotEmpty(widget?.itemList[0]?.netUrl) && PhotoPreviewToolUtils.isNetUrl(widget?.itemList[0]?.netUrl)){
      //编辑图片，无需上传
      SmartHomeUploadItemBean itemBean = widget?.itemList[0];
      _viewModel.editImage(context, widget?.shid, itemBean?.picid, itemBean?.backup, itemBean?.stid, itemBean?.style, widget?.router);
      return;
    }
    SmartHomeUploadService service =
    SmartHomeUploadService().setList(widget?.itemList, widget?.shid, getDefaultStid());
    if (service != null) {
      VgHudUtils.show(context, "正在上传");
      if ((widget?.itemList?.length ?? 0) > 0) {
        //多图上传
        service.multiUpload(VgBaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          VgHudUtils.hide(AppMain.context);
          VgToastUtils.toast(AppMain.context, "上传完成");
          RouterUtils.popUntil(context, widget?.router??SmartHomeOneDetailsPage.ROUTER);
        }, onError: (msg) {
          VgHudUtils.hide(context);
          print("MediaLibraryIndexPage上传失败:" + msg);
          VgToastUtils.toast(AppMain.context, "上传失败");
          RouterUtils.popUntil(context, widget?.router??SmartHomeOneDetailsPage.ROUTER);
        }));
      }
    }
  }

  Widget _toGridPage(){
    return Expanded(
      child: GridView.builder(
        padding: EdgeInsets.only(
            left: 15,
            right: 15,
            bottom: getNavHeightDistance(context)
        ),
        itemCount: widget?.itemList?.length ?? 0,
        physics: BouncingScrollPhysics(),
        shrinkWrap: true,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: 10,
          crossAxisSpacing: 5,
          childAspectRatio: 170 / 210,
        ),
        itemBuilder: (BuildContext context, int index) {
          return _toGridItemWidget(context, index, widget?.itemList?.elementAt(index));
        },
        controller: _scrollController,
      ),
    );
  }

  Widget _toGridItemWidget(BuildContext context, int index, SmartHomeUploadItemBean itemBean){
    _imgContainerWidth = (ScreenUtils.screenW(context) - 30 - 5)/2;
    _imgContainerHeight = (_imgContainerWidth * 210)/170;
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){

      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Column(
          children: [
            Container(
              height: _imgContainerWidth,
              width: _imgContainerWidth,
              color: Colors.white,
              child: Stack(
                children: [
                  Container(
                    height: _imgContainerWidth,
                    width: _imgContainerWidth,
                    child: VgCacheNetWorkImage(
                      itemBean?.getLocalPicUrl() ?? "",
                      fit: BoxFit.cover,
                      imageQualityType: ImageQualityType.high,),
                  ),
                  Align(
                    alignment: Alignment.topRight,
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: (){
                        setState(() {
                          widget?.itemList?.removeAt(index);
                        });
                        if(widget?.itemList?.length == 0){
                          RouterUtils.popUntil(context, widget?.router);
                        }
                        // bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
                        //   title: "提示",
                        //   content: "删除后不可恢复，确认删除当前文件？",
                        //   cancelText: "取消",
                        //   confirmText: "确认",
                        //   confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                        //   cancelBgColor: Color(0xFFF6F7F9),
                        //   titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                        //   contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                        //   widgetBgColor: Colors.white,
                        // );
                        // if (result ?? false) {
                        //   setState(() {
                        //     widget?.itemList?.removeAt(index);
                        //   });
                        //   if(widget?.itemList?.length == 0){
                        //     RouterUtils.popUntil(context, widget?.router);
                        //   }
                        // }
                      },
                      child: Padding(
                        padding: EdgeInsets.all(8),
                        child: Image.asset(
                          "images/icon_delete_img.png",
                          width: 15,
                          height: 15,
                        ),
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.center,
                    child: Visibility(
                      visible: itemBean.isVideo(),
                      child: Opacity(
                        opacity: 0.5,
                        child: Image.asset(
                          "images/video_play_ico.png",
                          width: 40,
                        ),
                      ),
                    ),
                  ),
                  Visibility(
                    visible: StringUtils.isNotEmpty(itemBean?.backup??""),
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: (){
                        SmartHomeSetBackupDialog.navigatorPushDialog(context, backup: itemBean?.backup,
                            onConfirm: (value){
                              setState(() {
                                itemBean?.backup = value;
                                widget?.itemList[index] = itemBean;
                              });

                            },
                            onDelete: (){
                              setState(() {
                                itemBean?.backup = "";
                                widget?.itemList[index] = itemBean;
                              });
                            }
                        );
                      },
                      child: Align(
                        alignment: Alignment.bottomCenter,
                        child: Container(
                          height: 24,
                          padding: EdgeInsets.symmetric(horizontal: 8),
                          alignment: Alignment.center,
                          color: Color(0xFF000000).withOpacity(0.7),
                          child: Text(
                            "${itemBean?.backup??""}",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.white
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              height: _imgContainerHeight - _imgContainerWidth,
              alignment: Alignment.center,
              color: Colors.white,
              child: Row(
                children: [
                  _toCategoryWidget(_imgContainerWidth, index, itemBean),
                  Container(
                    width: 1,
                    height: 14,
                    color: Color(0xFFDDDDDD),
                  ),
                  _toStyleWidget(_imgContainerWidth, index, itemBean),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toCategoryWidget(double width, int index, SmartHomeUploadItemBean itemBean){
    return Expanded(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          SmartHomeSetImageCategoryDialog.navigatorPushDialog(context, itemBean?.stid, widget?.categoryList, (selectType){
            setState(() {
              itemBean?.stid = selectType?.stid;
              widget?.itemList[index] = itemBean;
            });
          });
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              _getCategoryById(itemBean?.stid)??"空间分类",
              style: TextStyle(
                  fontSize: 12,
                color: StringUtils.isNotEmpty(_getCategoryById(itemBean?.stid))?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0xFFB0B3BF),
              ),
            ),
            SizedBox(width: 4,),
            Image.asset(
              "images/icon_shape_arrow_down.png",
              color: Color(0xFFB0B3BF),
              width: 7,
              height: 4,
            ),
          ],
        ),
      ),
    );
  }

  ///选择风格
  Widget _toStyleWidget(double width, int index, SmartHomeUploadItemBean itemBean){
    String style = ConstantRepository.of().getStyleNameByStyle(itemBean?.style);
    return Expanded(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          SmartHomeSetImageStyleDialog.navigatorPushDialog(context, itemBean?.style, (style){
            setState(() {
              itemBean?.style = style;
              widget?.itemList[index] = itemBean;
            });
          });
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              StringUtils.isNotEmpty(style)?style:"选择风格",
              style: TextStyle(
                  fontSize: 12,
                color: StringUtils.isNotEmpty(style)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0xFFB0B3BF),
              ),
            ),
            SizedBox(width: 2,),
            Image.asset(
              "images/icon_shape_arrow_down.png",
              color: Color(0xFFB0B3BF),
              width: 7,
              height: 4,
            ),
          ],
        ),
      ),
    );
  }

  String _getCategoryById(String id){
    String name;
    for(int i = 0; i < widget?.categoryList?.length; i++){
      if(id == widget?.categoryList[i].stid && "全部" != widget?.categoryList[i].name){
        name = widget?.categoryList[i].name;
        break;
      }
    }
    // if("其他" == name){
    //   name = "其他空间";
    // }
    if(StringUtils.isNotEmpty(name) && (name.length??0) > 4){
      return name.substring(0, 4) + "...";
    }
    return name;
  }

}




